from dao.DAOQuanLyNhanVien import DaoQuanLyNhanVien
from datetime import datetime, datetime
from google.appengine.api import users
from google.appengine.ext import db
import json as simplejson
from models.HoaHongNhanVien import HoaHongNhanVien
from models.LoaiNhanVien import LoaiNhanVien
from models.NhanVien import NhanVien
from utils.permission_required import permission_required
import WSGI
import logging
import math
import webapp2

logger = logging.getLogger("GUIHoaHongNhanVien")

class GuiHoaHongNhanVien(webapp2.RequestHandler):
    priv = ''
    perm = 'QuanLy.HoaHongNhanVien'
    @permission_required
    def get(self):
        cbbTenNV, _ = DaoQuanLyNhanVien.getListNhanVien('', '', 1000, 0, '')
        lstNV = ''
        for i in range(0, cbbTenNV.__len__()):
            cbbTenNV[i]['tenNV'] = str(cbbTenNV[i]['id']) + ' - ' + cbbTenNV[i]['tenNV']
            lstNV += str(cbbTenNV[i]['id']) + ':' + cbbTenNV[i]['tenNV'] + ';'
        lstNV = lstNV[:-1]  
        nv = DaoQuanLyNhanVien.getNhanVienByUsername(users.get_current_user().nickname())
        lstPerm = DaoQuanLyNhanVien.getListStaffPriviledge(nv.key().id())
        lstMenu = []
        lstNewPerm = []
        for perm in lstPerm:
            lstMenu.append(perm[:perm.index('.')])
            lstNewPerm.append(perm.replace('.', '-'))
        lstMenu = list(set(lstMenu))
        template_values = {
                        'lstPerm': lstNewPerm,
                        'lstMenu': lstMenu,
                        'cbbTenNV': cbbTenNV,
                        'lstNV': lstNV,
                        'nickname': users.get_current_user().nickname(),
                        'signOutUrl': users.create_logout_url(self.request.uri)
        }

        template = WSGI.jinja_environment.get_template('/html/HoaHongNhanVien.html')
        self.response.out.write(template.render(template_values))


class JsonRequestHandler(webapp2.RequestHandler):
    
    def get(self):
        funcName = self.request.get('func')
        funcMapping = {'getListHoaHongNhanVien': 'getListHoaHongNhanVien',
                       'updateHoaHongNhanVien': 'updateHoaHongNhanVien',
                       'checkHoaHongNhanVien': 'checkHoaHongNhanVien'}
        func = getattr(self, funcMapping[funcName]);
        result = func();
        self.response.out.write(result)
    
    def post(self):
        return self.get()
    
    def getListHoaHongNhanVien(self):
        gridRowNum = int(self.request.get('rows'))
        pageNum = int(self.request.get('page'))
        maNV = self.request.get('maNV')
        rows, rowNum = DaoQuanLyNhanVien.getListHoaHongNhanVien(maNV, gridRowNum, int((pageNum-1)*gridRowNum))
        results = {'page': pageNum, 'total': math.ceil(float(rowNum)/gridRowNum), 'records':rowNum, 'rows':rows}
        return simplejson.dumps(results)
    
    def updateHoaHongNhanVien(self):
        id = self.request.get('id')
        if id != '_empty':
            hhnv = HoaHongNhanVien.get_by_id(int(id))
        else:
            hhnv = HoaHongNhanVien()
        oper = self.request.get('oper')
        logger.debug(oper)
        if oper == 'del':
            DaoQuanLyNhanVien.deleteHoaHongNhanVien(hhnv)
            return 1
        else:
            hhnv.maNV = int(self.request.get('maNV'))
            hhnv.tenNV = DaoQuanLyNhanVien.getNhanVienById(hhnv.maNV).tenNV
            hhnv.nhoNhat = long(self.request.get('nhoNhat'))
            hhnv.lonNhat = long(self.request.get('lonNhat'))
            hhnv.hoaHong = float(self.request.get('hoaHong'))
            
            DaoQuanLyNhanVien.createOrUpdateHoaHongNhanVien(hhnv)
            return 1
        
    def checkHoaHongNhanVien(self):
        maNV = self.request.get('maNV')
        rows,_ = DaoQuanLyNhanVien.getListHoaHongNhanVien(maNV, 10000, 0)
        old = None
        try:
            old = rows[0]
        except:
            return -1
        for item in rows[1:]:
            new = item
            if new['nhoNhat'] != old['lonNhat'] + 1:
                return 0
        return 1
        
        
            
        